<template>
  <div class="bg car-container">

    <!-- 查询区域 -->
    <div>
      <el-input style="width: 200px;" clearable prefix-icon="el-icon-truck"
                @keyup.enter.native="load(1)" placeholder="查询车牌号" v-model="number"></el-input>
      <el-input style="width: 200px; margin: 0 5px" clearable prefix-icon="el-icon-truck"
                @keyup.enter.native="load(1)" placeholder="查询备注" v-model="remark"></el-input>
      <el-button type="primary" style="margin: 0 5px" @click="load(1)">查询</el-button>
      <el-button type="info" style="margin: 0 5px" @click="reset">重置</el-button>
      <el-select style="margin: 0 5px" v-model="model" placeholder="筛选车俩类型">
        <el-option label="手动挡（C1）" value="手动挡（C1）"></el-option>
        <el-option label="自动挡（C2）" value="自动挡（C2）"></el-option>
      </el-select>
      <el-select style="margin: 0 5px" v-model="state" placeholder="筛选车俩状态">
        <el-option label="可预约" value="可预约"></el-option>
        <el-option label="维护中" value="维护中"></el-option>
        <el-option label="不可用" value="不可用"></el-option>
      </el-select>
    </div>

    <!-- 增删区域 -->
    <div style="margin: 10px 0; height: 35px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="info" plain v-if="user.role === '管理员'"
                 @click="exportData">批量导出</el-button>
      <el-upload action="http://localhost:9090/car/import"
                 v-if="user.role === '管理员'"
                 :on-success="handleImport"
                 :show-file-list="false"
                 style="display: inline-block; margin-left: 10px">
        <el-button type="info" plain>批量导入</el-button>
      </el-upload>
    </div>

    <!-- 数据表格区域 -->
    <el-table :data="tableData" stripe class="datatable"
              :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="brand" label="品牌" sortable></el-table-column>
      <el-table-column prop="model" label="类型" sortable></el-table-column>
      <el-table-column prop="number" label="车牌号" sortable>
        <template v-slot="scope">
          <span v-html="highlightNumber(scope.row.number)"></span>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" sortable></el-table-column>
      <el-table-column prop="date" label="购买日期" sortable></el-table-column>
      <el-table-column label="照片">
        <template v-slot="scope">
          <div style="display: flex; align-items: center">
            <el-image style="width: 50px; height: 50px;"
                      v-if="scope.row.image"
                      :src="scope.row.image"
                      :preview-src-list="[scope.row.image]">
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器区域 -->
    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[100, 200, 300, 400]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <!-- 步骤条 -->
    <div style="position: relative; top: 15px;">
      <el-steps :active="1" align-center>
        <el-step title="发布车辆信息" icon="el-icon-truck" description="请核实相关车辆信息"></el-step>
        <el-step title="学员预约车辆" icon="el-icon-truck" description="学员根据需求预约车辆"></el-step>
        <el-step title="审核处理" icon="el-icon-circle-check" description="处理人负责指导该学员和管理车辆"></el-step>
        <el-step title="完成预约" icon="el-icon-circle-check" description="在完成相关内容后即视为完成"></el-step>
        <el-step title=学员评价 icon="el-icon-document" description="学员可为相关教练和车辆进行评价"></el-step>
      </el-steps>
    </div>

    <!-- 编辑/新增对话框 -->
    <el-dialog title="车辆信息" :visible.sync="fromVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="车牌号" prop="number">
          <el-input v-model="form.number" @keyup.enter.native="save()"
                    placeholder="请输入车牌号"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" @keyup.enter.native="save()"
                    placeholder="请输入车辆品牌"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="model">
          <el-radio-group v-model="form.model">
            <el-radio label="手动挡（C1）"></el-radio>
            <el-radio label="自动挡（C2）"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio label="可预约"></el-radio>
            <el-radio label="不可用"></el-radio>
            <el-radio label="维护中"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="购买日期" prop="date">
          <el-input v-model="form.date" @keyup.enter.native="save()"
                    placeholder="请输入购买日期"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" @keyup.enter.native="save()"
                    placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item label="照片">
          <el-upload
              class="image-uploader"
              action="http://localhost:9090/file/upload"
              :headers="{ token: this.user.token }"
              :file-list="form.image? [form.image] : []"
              list-type="picture"
              :on-success="handleImageSuccess">
            <el-button type="primary">上传车辆照片</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>
export default {
  name: "Car_info",

  // 组件的数据对象
  data() {
    return {
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'), // 从本地存储获取用户信息
      tableData: [],  // 存储所有的车辆信息数据
      pageNum: 1,   // 当前页码
      pageSize: 5,  // 每页显示的数据条数
      number: '', // 查询的车牌号
      remark: '', // 查询的备注
      model: '', // 查询的类型
      state: '', // 查询的状态
      total: 0, // 数据的总数
      fromVisible: false, // 控制新增/编辑对话框的显示与隐藏
      form: {}, // 存储表单数据
      rules: {
        number: [{ required: true, message: '请输入车牌号', trigger: 'blur' }] // 表单验证规则
      },
      ids: [] // 存储选中的车辆 ID 数组
    }
  },

  // 组件创建时调用 load 方法加载数据
  created() {
    this.load()
  },

  methods: {
    // 高亮车牌号的方法
    highlightNumber(number) {
      if (!number || number.length < 6) return number;
      const prefix = number.substring(0, 2);
      const highlighted = `<span
style="color: red; border: 1px solid black;
font-size: 15px; margin-left: 5px;margin-right: 5px">${number.substring(2, 6)}</span>`;
      const suffix = number.substring(6);
      return prefix + highlighted + suffix;
    },
    // 批量删除的方法
    delBatch() {
      // 判断是否有选中的数据
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      // 弹出确认删除的提示框
      this.$confirm('您确认批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        // 发送删除请求
        this.$request.delete('/car/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {   // 操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误信息
          }
        })
      }).catch(() => {})
    },

    // 处理表格行选中变化的方法
    handleSelectionChange(rows) {   // 获取选中的行数据
      this.ids = rows.map(v => v.id)
    },

    // 删除单条数据的方法
    del(id) {
      // 弹出确认删除的提示框
      this.$confirm('您确认删除吗？', '确认删除', {type: "warning"}).then(response => {
        // 发送删除请求
        this.$request.delete('/car/delete/' + id).then(res => {
          if (res.code === '200') {   // 操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误信息
          }
        })
      }).catch(() => {})
    },

    // 批量导出 excel 的方法
    exportData() {
      // 判断是否有选中的数据，决定导出的范围
      if (!this.ids.length) {
        window.open('http://localhost:9090/car/export?remark=' + this.remark + '&number=' + this.number)
      } else {
        let idStr = this.ids.join(',')
        window.open('http://localhost:9090/car/export?ids=' + idStr)
      }
    },

    // 批量导入 excel 的方法
    handleImport(res, file, fileList) {
      if (res.code === '200') {
        this.$message.success("操作成功")
        this.load(1)
      } else {
        this.$message.error(res.msg)
      }
    },

    // 编辑数据的方法
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 深拷贝数据
      this.fromVisible = true   // 打开弹窗
    },

    // 新增数据的方法
    handleAdd() {   // 新增数据
      this.form = {model: '手动挡（C1）', state: '维护中', date: '2000-01-01'}
      this.fromVisible = true   // 打开弹窗
    },

    // 保存数据的方法
    save() {   // 保存按钮触发的逻辑
      // 表单验证
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 根据是否有 ID 判断是新增还是更新
          this.$request({
            url: this.form.id ? '/car/update' : '/car/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 保存成功
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误信息
            }
          })
        }
      })
    },

    // 重置查询条件的方法
    reset() {
      this.number = ''
      this.remark = ''
      this.model = ''
      this.state = ''
      this.load()
    },

    // 加载数据的方法
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      // 发送请求获取分页数据
      this.$request.get('/car/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          number: this.number,
          remark: this.remark,
          model: this.model,
          state: this.state,
          brand: '',
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },

    // 处理分页变化的方法
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },

    // 处理头像上传成功的方法
    handleImageSuccess(response, file, fileList) {
      this.form.image = response.data
    },
  }
}
</script>


<style>
.car-container {
  background: url('@/assets/bg/car.png') center/cover no-repeat;
}
</style>